<script setup lang="ts">
  import {
    queryInstBranchInfo,
    queryList,
    deleteBranch,
  } from '@/api/organization/nursing-home';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import { computed, ref } from 'vue';
  import useModeModalHandler from '@/hooks/arco/useModeModalHandler';
  import ListSelect from '@/components/list-select/index.vue';
  import { getAddrByCode } from '@/utils/address';
  import { queryBranchBuildingList } from '@/api/organization/building';
  import { useAutoRequest } from '@/hooks/arco/useAutoLoading';
  import { Message } from '@arco-design/web-vue';

  import Edit from './edit.vue';
  import EditBuilding from './edit-building.vue';

  const deleteBranchStr = '删除院区';

  const visible = ref(false);

  const deleteInputValue = ref('');

  const deleteBtnDisabled = computed(() => {
    return deleteInputValue.value !== deleteBranchStr;
  });

  const pageTable = useSkeleton<any>({
    apiFun: queryList,
  });

  const checkIndex = ref(-1);

  const currentBranch = ref();

  const editDrawer = useModeModalHandler({
    onSuccess() {
      pageTable.retry();
    },
  });

  const generateBranchData = (data: any) => {
    const areaStr = getAddrByCode(
      data.provinceCode,
      data.cityCode,
      data.districtCode
    );

    return [
      {
        label: '院区名称',
        value: data.name,
      },
      {
        label: '院区简称',
        value: data.shortName,
      },
      {
        label: '院区状态',
        value: data.statusLabel,
      },
      {
        label: '所在地区',
        value: areaStr,
      },
      {
        label: '详细地址',
        value: data.address,
      },
    ];
  };

  const generateBuildingData = (data: any) => {
    return [
      {
        label: '建筑状态',
        value: data.statusLabel,
      },
      {
        label: '建筑层高',
        value: data.floorNum,
      },
      {
        label: '使用范围',
        value: `1-${data.maxFloor}`,
      },
    ];
  };

  const detailSkeleton = useSkeleton<any>({
    apiFun: queryInstBranchInfo,
    transformDataFun(data) {
      return generateBranchData(data);
    },
    immediate: false,
  });

  const buildListSkeleton = useSkeleton({
    apiFun: queryBranchBuildingList,
    immediate: false,
    isEmpty() {
      return false;
    },
  });

  const goToDetail = (record: any) => {
    currentBranch.value = record;
    detailSkeleton.execute(record.id);
    buildListSkeleton.execute(record.id);
  };

  const onItemCheck = (item: any, index: number) => {
    checkIndex.value = index;
    goToDetail(item);
  };

  const buildingModal = useModeModalHandler({
    onSuccess() {
      buildListSkeleton.retry();
    },
  });

  const addBuilding = () => {
    buildingModal.showAdd({ branchId: currentBranch.value.id });
  };

  const [deleteLd, deleteReq] = useAutoRequest(
    () => deleteBranch(currentBranch.value.id),
    {
      onSuccess() {
        visible.value = false;
        Message.success('删除成功');
        pageTable.retry();
      },
    }
  );

  const onDeleteBranch = () => {
    visible.value = true;
    deleteInputValue.value = '';
  };
</script>

<template>
  <div class="h-full">
    <a-modal
      v-model:visible="visible"
      body-class="p-0"
      :footer="false"
      unmount-on-close
    >
      <template #title>
        <span class="font-semibold text-[16px]">删除院区</span>
      </template>
      <div class="flex flex-col">
        <a-alert type="warning">在删除之前请仔细阅读下面的信息</a-alert>
        <div class="p-3 flex flex-col gap-2 text-[13px]">
          <span>
            <span class="font-semibold">删除影响：</span>
            与之关联的建筑、房间和床位将一并被删除；与之关联的员工
            将取消关联；与之关联的设备将取消关联且设备状态改为禁用；与之关联的长者
            将取消关联且用药计划将作废；
          </span>

          <span class="font-semibold">
            请在下方输入
            <span class="text-red-500">"{{ deleteBranchStr }}"</span>
            进行校验。
          </span>

          <a-input
            v-model="deleteInputValue"
            :placeholder="'请输入' + deleteBranchStr"
          />
        </div>
        <a-divider margin="0" />
        <a-button
          class="m-3"
          type="primary"
          :disabled="deleteBtnDisabled"
          :loading="deleteLd"
          @click="deleteReq"
        >
          确定删除
        </a-button>
      </div>
    </a-modal>
    <Edit v-bind="editDrawer.bindProps" />
    <EditBuilding v-bind="buildingModal.bindProps" />
    <div class="flex gap-5 h-full">
      <div class="p-0 gap-5 flex flex-col round">
        <a-button
          class="shadow-md h-[40px] text-[16px]"
          type="primary"
          size="large"
          @click="editDrawer.showAdd()"
        >
          <template #icon>
            <icon-plus />
          </template>
          <span>新建院区</span>
        </a-button>
        <!-- <a-divider margin="0" /> -->
        <skeleton-view
          v-slot="{ data }"
          class="w-[280px]"
          v-bind="pageTable.bindProps"
        >
          <ListSelect :data="data" @change="onItemCheck" />
        </skeleton-view>
      </div>

      <!-- <a-divider margin="0" direction="vertical" /> -->

      <div class="flex-1 py-2 px-4 border rounded shadow overflow-y-auto">
        <a-empty v-if="checkIndex == -1" class="mt-10"> 请选择院区 </a-empty>
        <a-tabs
          v-else
          class="h-full"
          default-active-key="1"
          size="large"
          justify
        >
          <a-tab-pane key="1">
            <template #title>
              <span class="text-[16px]">院区信息</span>
            </template>
            <div class="p-2 h-full">
              <SkeletonView
                v-slot="{ data }"
                class="h-full"
                v-bind="detailSkeleton.bindProps"
              >
                <div class="flex flex-col h-full pl-2">
                  <a-descriptions
                    class="flex-1"
                    :column="1"
                    :data="data"
                    size="large"
                  >
                  </a-descriptions>
                  <a-divider margin="14px" />
                  <a-space class="self-end" size="medium">
                    <ae-button purpose="delete" @click="onDeleteBranch">
                      <template #icon>
                        <icon-delete />
                      </template>
                      删除
                    </ae-button>
                    <ae-button
                      purpose="edit"
                      @click="editDrawer.showEdit(currentBranch)"
                    >
                      <template #icon>
                        <icon-edit />
                      </template>
                      编辑
                    </ae-button>
                  </a-space>
                </div>
              </SkeletonView>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2">
            <template #title>
              <span class="text-[16px]">建筑信息</span>
            </template>
            <div class="p-2">
              <SkeletonView
                v-slot="{ data }"
                v-bind="buildListSkeleton.bindProps"
              >
                <a-grid
                  :cols="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }"
                  :col-gap="12"
                  :row-gap="12"
                >
                  <a-grid-item>
                    <a-card
                      class="card-demo border-dashed h-[170px]"
                      hoverable
                      :body-style="{
                        height: '100%',
                      }"
                    >
                      <div
                        class="flex flex-col p-0 gap-2 h-full justify-center items-center cursor-pointer"
                        @click="addBuilding"
                      >
                        <span><icon-plus size="20" /></span>
                        <span class="text-[16px]"> 新建建筑 </span>
                      </div>
                    </a-card>
                  </a-grid-item>
                  <a-grid-item v-for="(building, index) in data" :key="index">
                    <a-card class="card-demo" :title="building.name" hoverable>
                      <template #extra>
                        <a-link
                          class="h-full"
                          v-bind="buildingModal.openBtn('detail', building)"
                        >
                          查看
                        </a-link>
                      </template>
                      <a-descriptions
                        :column="1"
                        :data="generateBuildingData(building)"
                        :align="{ label: 'right' }"
                      >
                      </a-descriptions>
                    </a-card>
                  </a-grid-item>
                </a-grid>
              </SkeletonView>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .card-demo {
    transition-property: all;

    :deep(.arco-card-header-extra) {
      height: 100%;
    }
  }
  .card-demo:hover {
    transform: translateY(-4px);
  }
</style>
